<script setup>
import { ref, onMounted } from 'vue'
import axios from '../utils/axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import { Plus } from '@element-plus/icons-vue'

const userStore = useUserStore()
const loading = ref(false)
const stats = ref({
  totalQuestions: 0,
  wrongQuestionsCount: 0,
  todayQuestions: 0
})

// 添加 token 的响应式引用
const token = ref(localStorage.getItem('token') || '')

// 用户信息表单
const userForm = ref({
  username: '',
  email: '',
  phone: '',
  avatar: ''
})

// 修改密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 添加表单引用
const userFormRef = ref(null)
const passwordFormRef = ref(null)

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await axios.get('/statistics')
    stats.value = response.data
  } catch (error) {
    console.error('Error fetching stats:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const response = await axios.get('/users/profile')
    userForm.value = response.data
  } catch (error) {
    console.error('Error fetching user info:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 更新用户信息
const updateUserInfo = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('Updating user info:', userForm.value) // 添加日志
        const response = await axios.put('/users/profile', {
          email: userForm.value.email,
          phone: userForm.value.phone
        })
        ElMessage.success('个人信息更新成功')
        userForm.value = response.data
        await userStore.fetchUserInfo()
      } catch (error) {
        console.error('Error updating user info:', error)
        ElMessage.error('更新失败：' + (error.response?.data?.message || '未知错误'))
      } finally {
        loading.value = false
      }
    } else {
      console.log('Form validation failed') // 添加日志
    }
  })
}

// 修改密码
const updatePassword = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await axios.put('/users/password', {
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        })
        ElMessage.success('密码修改成功')
        passwordForm.value = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        console.error('Error updating password:', error)
        ElMessage.error('修改失败：' + (error.response?.data?.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
  })
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  userForm.value.avatar = response.data
  ElMessage.success('头像上传成功')
}

// 头像上传失败
const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

// 在组件挂载时更新 token
onMounted(() => {
  token.value = localStorage.getItem('token') || ''
  fetchStats()
  fetchUserInfo()
})
</script>

<template>
  <div class="dashboard-container">
    <!-- 统计信息卡片 -->
    <el-card class="stats-card">
      <template #header>
        <div class="card-header">
          <span>统计信息</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-title">总提问次数</div>
            <div class="stat-value">{{ stats.totalQuestions }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-title">备忘录个数</div>
            <div class="stat-value">{{ stats.wrongQuestionsCount }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-title">今日提问次数</div>
            <div class="stat-value">{{ stats.todayQuestions }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 个人中心卡片 -->
    <el-card class="profile-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="avatar-container">
            <el-upload
              class="avatar-uploader"
              action="/api/users/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
              :headers="{ 'Authorization': `Bearer ${token}` }"
            >
              <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-hint">点击上传头像</div>
          </div>
        </el-col>

        <el-col :span="18">
          <el-tabs>
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息">
              <el-form
                ref="userFormRef"
                :model="userForm"
                :rules="rules"
                label-width="80px"
                @submit.prevent
              >
                <el-form-item label="用户名">
                  <el-input v-model="userForm.username" disabled />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userForm.phone" />
                </el-form-item>
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="updateUserInfo(userFormRef)"
                  >
                    保存修改
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 修改密码 -->
            <el-tab-pane label="修改密码">
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="rules"
                label-width="80px"
                @submit.prevent
              >
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input
                    v-model="passwordForm.oldPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="updatePassword(passwordFormRef)"
                  >
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.profile-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.avatar-container {
  text-align: center;
  padding: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  margin: 0 auto;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.upload-hint {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

:deep(.el-form-item__content) {
  max-width: 300px;
}
</style> 